import sys
import json
import subprocess
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QLabel, QLineEdit, QTextEdit, QPushButton, QMessageBox,
                             QHBoxLayout, QGroupBox, QFrame)
from PyQt6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QTimer
from PyQt6.QtGui import QFont, QPalette, QColor

class ConfigWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('配置编辑器')
        self.setGeometry(100, 100, 800, 600)
        self.process = None
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f5;
            }
            QGroupBox {
                border: 2px solid #ddd;
                border-radius: 8px;
                margin-top: 1em;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
            }
            QLabel {
                font-size: 14px;
                color: #333;
                font-weight: bold;
            }
            QLineEdit, QTextEdit {
                border: 2px solid #ddd;
                border-radius: 4px;
                padding: 5px;
                background-color: white;
                font-size: 13px;
            }
            QLineEdit:focus, QTextEdit:focus {
                border-color: #4a9eff;
            }
            QPushButton {
                background-color: #4a9eff;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2d6da3;
            }
        """)

        # 创建中央部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # API设置组
        api_group = QGroupBox('API 设置')
        api_layout = QVBoxLayout()
        api_layout.setSpacing(8)
        
        api_label = QLabel('API Key:')
        self.api_key_input = QLineEdit()
        self.api_key_input.setPlaceholderText('请输入您的API密钥')
        api_layout.addWidget(api_label)
        api_layout.addWidget(self.api_key_input)
        api_group.setLayout(api_layout)
        layout.addWidget(api_group)

        # 系统设置组
        system_group = QGroupBox('系统设置')
        system_layout = QVBoxLayout()
        system_layout.setSpacing(8)
        
        prompt_label = QLabel('System Prompt:')
        self.system_prompt_input = QTextEdit()
        self.system_prompt_input.setMinimumHeight(100)
        self.system_prompt_input.setPlaceholderText('请输入系统提示词')
        system_layout.addWidget(prompt_label)
        system_layout.addWidget(self.system_prompt_input)
        system_group.setLayout(system_layout)
        layout.addWidget(system_group)

        # 监听设置组
        listen_group = QGroupBox('监听设置')
        listen_layout = QVBoxLayout()
        listen_layout.setSpacing(8)
        
        listen_label = QLabel('Listen List (每行一个名字):')
        self.listen_list_input = QTextEdit()
        self.listen_list_input.setMinimumHeight(100)
        self.listen_list_input.setPlaceholderText('请输入需要监听的名字列表\n每行输入一个名字')
        listen_layout.addWidget(listen_label)
        listen_layout.addWidget(self.listen_list_input)
        
        wait_label = QLabel('Merge Wait Time (秒):')
        self.merge_wait_time_input = QLineEdit()
        self.merge_wait_time_input.setPlaceholderText('请输入合并等待时间')
        listen_layout.addWidget(wait_label)
        listen_layout.addWidget(self.merge_wait_time_input)
        listen_group.setLayout(listen_layout)
        layout.addWidget(listen_group)

        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 0)
        button_layout.setSpacing(15)
        
        # 保存按钮
        save_button = QPushButton('保存配置')
        save_button.setMinimumWidth(120)
        save_button.clicked.connect(self.save_config)
        button_layout.addWidget(save_button)
        
        # 运行按钮
        self.run_button = QPushButton('运行程序')
        self.run_button.setMinimumWidth(120)
        self.run_button.clicked.connect(self.toggle_program)
        button_layout.addWidget(self.run_button)
        
        # 添加弹性空间，使按钮居中
        button_layout.addStretch(1)
        button_layout.insertStretch(0, 1)
        
        layout.addLayout(button_layout)

        # 加载现有配置
        self.load_config()

    def load_config(self):
        try:
            with open('config.py', 'r', encoding='utf-8') as f:
                content = f.read()
                # 提取config字典
                exec(content, globals())
                config_dict = globals()['config']

                self.api_key_input.setText(config_dict['api_key'])
                self.system_prompt_input.setText(config_dict['system_prompt'])
                self.listen_list_input.setText('\n'.join(config_dict['listen_list']))
                self.merge_wait_time_input.setText(str(config_dict['merge_wait_time']))
        except Exception as e:
            QMessageBox.warning(self, '错误', f'加载配置文件失败：{str(e)}')

    def save_config(self):
        try:
            config_dict = {
                'api_key': self.api_key_input.text(),
                'system_prompt': self.system_prompt_input.toPlainText(),
                'listen_list': [name.strip() for name in self.listen_list_input.toPlainText().split('\n') if name.strip()],
                'merge_wait_time': float(self.merge_wait_time_input.text())
            }

            # 生成配置文件内容
            config_content = f"config = {json.dumps(config_dict, ensure_ascii=False, indent=4)}"

            # 保存到文件
            with open('config.py', 'w', encoding='utf-8') as f:
                f.write(config_content)

            QMessageBox.information(self, '成功', '配置已保存')
            return config_dict
        except Exception as e:
            QMessageBox.warning(self, '错误', f'保存配置失败：{str(e)}')
            return None

    def toggle_program(self):
        if not self.process:
            self.run_program()
        else:
            self.stop_program()

    def run_program(self):
        try:
            # 先保存当前配置
            config_dict = self.save_config()
            if config_dict is None:
                return
            
            # 更新按钮状态
            self.run_button.setText('结束程序')
            
            # 返回配置以供主程序使用
            return config_dict
            
        except Exception as e:
            QMessageBox.warning(self, '错误', f'启动程序失败：{str(e)}')
            self.process = None
            self.run_button.setText('运行程序')
            return None
    
    def stop_program(self):
        self.run_button.setText('运行程序')
        QMessageBox.information(self, '成功', '程序已停止')